<script setup lang="ts">
import { ref, nextTick } from 'vue'
import Card from './ui/Card.vue'
import ScrollArea from './ui/ScrollArea.vue'
import Button from './ui/Button.vue'
import Input from './ui/Input.vue'
import { Send } from 'lucide-vue-next'
import { llmService } from '../api'
import type { ChatMessage } from '../types'

interface Message {
  id: number
  role: 'user' | 'agent'
  content: string
  timestamp: string
}

const messages = ref<Message[]>([
  {
    id: 1,
    role: 'agent',
    content: '你好！我是广场中心 Agent。欢迎来到 Agent 指挥中心。我可以帮你处理各种任务，请告诉我你需要什么帮助。',
    timestamp: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
])

const inputMessage = ref('')
const isLoading = ref(false)
const scrollAreaRef = ref<HTMLElement>()

const scrollToBottom = async () => {
  await nextTick()
  if (scrollAreaRef.value) {
    const viewport = scrollAreaRef.value.querySelector('[data-radix-scroll-area-viewport]')
    if (viewport) {
      viewport.scrollTop = viewport.scrollHeight
    }
  }
}

// 将消息转换为API格式
const convertToApiHistory = (msgs: Message[]): ChatMessage[] => {
  return msgs
    .filter(msg => msg.role !== 'agent' || msg.id !== 1) // 排除欢迎消息
    .map(msg => ({
      role: msg.role === 'agent' ? 'assistant' : 'user',
      content: msg.content
    }))
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage: Message = {
    id: messages.value.length + 1,
    role: 'user',
    content: inputMessage.value,
    timestamp: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  messages.value.push(userMessage)
  const userInput = inputMessage.value
  inputMessage.value = ''

  await scrollToBottom()

  // 调用真实的LLM API
  isLoading.value = true

  try {
    const history = convertToApiHistory(messages.value.slice(0, -1)) // 不包括当前用户消息
    const response = await llmService.chat({
      message: userInput,
      history: history.length > 0 ? history : undefined,
      provider: 'openai'
    })

    const agentMessage: Message = {
      id: messages.value.length + 1,
      role: 'agent',
      content: response.message,
      timestamp: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
    messages.value.push(agentMessage)
  } catch (error: any) {
    console.error('发送消息失败:', error)
    const errorMessage: Message = {
      id: messages.value.length + 1,
      role: 'agent',
      content: `抱歉，我遇到了一些问题。错误信息：${error.response?.data?.message || error.message || '未知错误'}。请稍后重试。`,
      timestamp: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
    messages.value.push(errorMessage)
  } finally {
    isLoading.value = false
    await scrollToBottom()
  }
}

const handleKeyPress = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- 标题栏 -->
    <div class="p-4 border-b bg-background">
      <h1 class="text-2xl font-bold">Agent 指挥中心</h1>
      <p class="text-sm text-muted-foreground">与广场中心 Agent 对话</p>
    </div>

    <!-- 消息列表 -->
    <ScrollArea ref="scrollAreaRef" class="flex-1 p-4">
      <div class="max-w-4xl mx-auto space-y-4">
        <div
          v-for="message in messages"
          :key="message.id"
          :class="[
            'flex',
            message.role === 'user' ? 'justify-end' : 'justify-start'
          ]"
        >
          <Card
            :class="[
              'max-w-[80%] p-4',
              message.role === 'user'
                ? 'bg-primary text-primary-foreground'
                : 'bg-muted'
            ]"
          >
            <div class="flex items-start gap-2 mb-2">
              <span class="text-xs font-semibold">
                {{ message.role === 'user' ? '你' : '广场中心' }}
              </span>
              <span class="text-xs opacity-70 ml-auto">
                {{ message.timestamp }}
              </span>
            </div>
            <p class="text-sm whitespace-pre-wrap">{{ message.content }}</p>
          </Card>
        </div>

        <!-- 加载指示器 -->
        <div v-if="isLoading" class="flex justify-start">
          <Card class="max-w-[80%] p-4 bg-muted">
            <div class="flex items-center gap-2">
              <span class="text-xs font-semibold">广场中心</span>
            </div>
            <div class="flex gap-1 mt-2">
              <span class="w-2 h-2 bg-primary rounded-full animate-bounce" style="animation-delay: 0ms"></span>
              <span class="w-2 h-2 bg-primary rounded-full animate-bounce" style="animation-delay: 150ms"></span>
              <span class="w-2 h-2 bg-primary rounded-full animate-bounce" style="animation-delay: 300ms"></span>
            </div>
          </Card>
        </div>
      </div>
    </ScrollArea>

    <!-- 输入区域 -->
    <div class="p-4 border-t bg-background">
      <div class="max-w-4xl mx-auto flex gap-2">
        <Input
          v-model="inputMessage"
          placeholder="输入消息..."
          class="flex-1"
          :disabled="isLoading"
          @keypress="handleKeyPress"
        />
        <Button
          @click="sendMessage"
          :disabled="!inputMessage.trim() || isLoading"
        >
          <Send class="w-4 h-4" />
        </Button>
      </div>
    </div>
  </div>
</template>
